<template>
    <view class="share-page">
        <view class="share-page-preview">
            <image class="share-page-img" :src="bgUrl" :draggable="false" mode="widthFix"></image>
            <view class="share-preview-bottom">
                <image class="share-page-avatar" :src="avatarUrl || defaultImg" :draggable="false"></image>
                <view class="share-page-info">
                    <text class=".nickname">{{ nickname }}</text>
                    <text>扫码进店逛逛</text>
                </view>
                <!-- todo:二维码 -->
                <image :src="qrCodeUrl || defaultImg" class="share-page-qrcode" :draggable="false"></image>
            </view>
        </view>
        <canvasdrawer
            v-if="painting?.views?.length"
            :painting="painting"
            class="canvasdrawer"
            @getImage="eventGetImage" />
        <!-- todo:二维码没生成不能点击图片 -->
        <view class="share-page-btn">
            <button class="btn-big" @tap="eventSave">保存图片至相册</button>
        </view>
        <!-- 权限控制弹窗 -->
        <uni-popup class="photo-view-default" ref="photoPopupRef" :mask-click="true">
            <view class="photo-popup">
                <view class="photo-popup-tip">您已禁止了添加到相册权限，请前往权限页面设置开启</view>
                <view class="photo-last"><view class="photo-btn" @tap="handleRoutePermission"> 立即设置 </view></view>
            </view>
        </uni-popup>
        <!-- 隐私监听 -->
        <el-privacy-listener-popup :is-handle-tab-bar="false"></el-privacy-listener-popup>
    </view>
</template>
<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import storage from '@/commons/storage';
import { getImgOssUrl } from '@/commons/utils';
import request from '@/request';
import canvasdrawer from '@/components/uniapp-canvas-drawer/uniapp-canvas-drawer';

const shareImage = ref();

let painting = reactive({});
const nickname = storage.get('nickname') || '你的好友';
const avatarUrl = storage.get('avatar') || getImgOssUrl('/ui-prod-2.7.0/avatar.png');
const bgUrl = getImgOssUrl('/ui-prod-2.8.0/invite-distributi.png');
const defaultImg = ref(getImgOssUrl('/ui-prod-2.0.0/errorImg.png'));
let qrCodeUrl = ref();
let photoPopupRef = ref();

const getQrcode = async () => {
    // todo：分销员申请页面，且需要待上邀请人id,且因为对方可能已经是分销员，怎么判断对方已经是分销员
    uni.showLoading({
        title: '生成小程序码中...',
        mask: true
    });
    const { data } = await request('generateWxQrcode', {
        page: 'pages-user/distributi/distributiApply/index',
        scene: `i=${storage.get('userId')}&s=${storage.get('ZW_SHOP_ID')}&ch=2`
    });
    qrCodeUrl.value = (data || {})?.url;
    uni.hideLoading();
};

const eventGetImage = res => {
    uni.hideLoading();

    // const { tempFilePath, errMsg } = event.detail

    // let result = null;
    let tempFilePath = null;
    let errMsg = null;

    // #ifdef MP-WEIXIN
    // console.log('event', event);
    // result = event.detail.__args__;
    // tempFilePath = result[0].tempFilePath;
    // errMsg = result[0].errMsg;
    // #endif

    // #ifdef APP-PLUS
    // result = event;
    tempFilePath = res?.tempFilePath;
    errMsg = res?.errMsg;
    // #endif

    if (res?.errMsg === 'canvasdrawer:ok') {
        // #ifdef MP-WEIXIN
        shareImage.value = res?.tempFilePath;
        // #endif

        // #ifdef APP-PLUS
        // shareImage.value = 'file:///' + plus.io.convertLocalFileSystemURL(tempFilePath);
        // #endif
        // painting = {};
        uni.saveImageToPhotosAlbum({
            filePath: shareImage.value,
            success(res) {
                photoPopupRef?.value.close();
                uni.showToast({
                    title: '图片保存成功~',
                    icon: 'success',
                    duration: 2000
                });
            },
            fail(error) {
                if (error?.errMsg.includes('deny')) {
                    photoPopupRef?.value.open('center');
                }
            }
        });
    } else {
    }
};

const eventSave = () => {
    if (!shareImage.value) {
        Object.assign(painting, {
            width: null,
            height: null,
            isPixelRatio: false,
            views: []
        });
        getPainting();
    } else {
        uni.saveImageToPhotosAlbum({
            filePath: shareImage.value,
            success(res) {
                photoPopupRef?.value.close();
                uni.showToast({
                    title: '图片保存成功~',
                    icon: 'success',
                    duration: 2000
                });
            },
            fail(error) {
                if (error?.errMsg.includes('deny')) {
                    photoPopupRef?.value.open('center');
                }
            }
        });
    }
};

const getPainting = () => {
    uni.showLoading({
        title: '图片生成中...',
        mask: true
    });
    // todo:之后根据屏幕分辨率计算高
    const { windowWidth, windowHeight } = uni.getSystemInfoSync();
    const width = windowWidth - 32;
    const height = width * 1.77;
    Object.assign(painting, {
        width,
        height,
        isPixelRatio: true,
        views: [
            // {
            //     type: 'image',
            //     url: bgUrl,
            //     top: 0,
            //     left: 0,
            //     width: width,
            //     height: width * 1.46
            // },
            // {
            //     type: 'image',
            //     url: avatarUrl,
            //     top: height - 74,
            //     left: 16,
            //     width: 56,
            //     height: 56
            // },
            {
                type: 'image',
                url: bgUrl,
                top: 0,
                left: 0,
                width: width,
                height: width <= 320 ? width * 1.4 : width * 1.48 // <= 320 iphone5类似的机型
            },
            {
                type: 'image',
                url: avatarUrl || defaultImg.value,
                top: height - 78,
                left: 16,
                width: 56,
                height: 56,
                isCircle: true
            },
            {
                type: 'image',
                url: qrCodeUrl.value || defaultImg.value,
                top: height - 90,
                left: width - 162 + 56 + 16,
                width: 74,
                height: 74
            },
            {
                type: 'text',
                content: nickname,
                fontSize: 16,
                lineHeight: 22,
                color: '#333333',
                textAlign: 'left',
                top: height - 74,
                left: 84,
                width: width - 185,
                MaxLineNumber: 1,
                breakWord: true,
                bolder: true
            },
            {
                type: 'text',
                content: '扫码进店逛逛',
                fontSize: 14,
                lineHeight: 14,
                color: '#999999',
                textAlign: 'left',
                top: height - 42,
                left: 84,
                width: 200,
                MaxLineNumber: 1,
                breakWord: true
            }
        ]
    });
};

const handleRoutePermission = () => {
    photoPopupRef?.value.close();
    uni.openSetting({});
};

uni.setNavigationBarTitle({ title: `邀请${storage.get('dtbName')}` });
onMounted(async () => {
    getQrcode();
});
</script>
<style lang="scss" scoped src="./index.scss"></style>
